package com.xhtt.fzxy.console;

import com.xhtt.fzxy.console.handler.BaseHandler;
import com.xhtt.fzxy.console.handler.post.GetServerInfo;
import com.xhtt.fzxy.console.handler.post.Login;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * auth: WenYF
 * date: 2018/5/4
 */
public class ConsoleServlet extends HttpServlet {
    public static final Logger Log = LoggerFactory.getLogger(ConsoleServlet.class);
    
    private HashMap<String, BaseHandler> getHandlers = new HashMap<>();
    private HashMap<String, BaseHandler> postHandlers = new HashMap<>();
    
    
    @Override
    public void init() throws ServletException {
        super.init();
        Log.info("ConsoleServlet init");

        postHandlers.put("login", new Login());
        postHandlers.put("get_server_info", new GetServerInfo());
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Log.info("ConsoleServlet doGet");
        String target = req.getRequestURL().toString();
        int index = target.lastIndexOf("/");
        String method = target.substring(index + 1, target.length());

        BaseHandler handler = getHandlers.get(method);
        if (handler != null) {
            handler.baseProcess(req, resp);
        } else {
            super.doGet(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Log.info("ConsoleServlet doPost");
        String target = req.getRequestURL().toString();
        int index = target.lastIndexOf("/");
        String method = target.substring(index + 1, target.length());
        
        BaseHandler handler = postHandlers.get(method);
        if (handler != null) {
            handler.baseProcess(req, resp);
        } else {
            super.doPost(req, resp);
        }
    }
}
